<?php
/**
 * This page handles the 'editView'
 * editView is the editing page for a project. Found at /edit/([a-zA-Z0-9_]+)
 * 
 * This page can only be accessed using mod_rewrite.
 */

    $fileprefix = '../';
    if(isset($_ECLIPSEMDE['ROOT_WD']) === true)
	$fileprefix = $_ECLIPSEMDE['ROOT_WD'];
    require_once($fileprefix.'SiteIncludes.GLOBAL.php');
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	$gVAR['e'] = '404';
	require_once('error_handler.php');
	die();
    }
    
    
    /**
     * This is the switch that handles the difference between admin and user edits.
     * It is set in www-admin/project.php, and if it is not set, it is set to false here.
     * This is how the script decides if you are an admin editor or not. 
     */
    if(isset($_ADMINEDIT) === false) {
	$_ADMINEDIT = false;
    }
    
    // Ensure all variables needed are set
    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false && isset($gVAR['alias']) !== false) {
	try {
	    $Project =& $ProjectStash->get($gVAR['alias']);
	    // Tool Name in the JS
	    $TemplateEngine->add_preloadScript('<script type="text/javascript">var tool_name=\''.$Project->getAlias().'\';</script>');
	    
	    if($Project->userCanEdit($_LOGGEDINUSER->get_userid(), $_ADMINEDIT) === true) {
		
    /**
     * We are on an editing page, so we will add the timeout warning js 
     * & add the tooltip manager
     */
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/inactivityWarning.js"></script>');
    $TemplateEngine->add_postloadScript('<script type="text/javascript">inactivity_hour();</script>');
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/ToolTip.js"></script>');
    
    // Add Javascript for cleanup script and confirmer script
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/ajaxCleanup.js"></script>');
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/ajaxConfirmer.js"></script>');
    
    // Add Javascript for Settings, Add iframe for callback
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/settingsUpdate.js"></script>');
    $TemplateEngine->add_postloadScript('<iframe src="" style="display: none; visibility: hidden; height: 0px; width: 0px;" id="edjx_settings_update" name="edjx_settings_update"></iframe>');
		
    // Add Javascript for tags
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/tagsEdit.js"></script>');
    
    // Add Javascript for twitter
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/twitterEdit.js"></script>');
    
    // Add Javascript for user contrib
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/userContribEdit.js"></script>');
    
    // Add Javascript for Blogs/Docs/Sites
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/siteEdit.js"></script>');
    $blog_docs_site_setupJS = <<<EOSJS
	<script type="text/javascript">
	    setTimeout('SiteEDJX.init(\'blog\')', '1250');
	    setTimeout('SiteEDJX.init(\'docs\')', '1250');
	    setTimeout('SiteEDJX.init(\'site\')', '1250');
	    setTimeout('SiteEDJX.init(\'rss\')', '1250');
	</script>
EOSJS;
    $TemplateEngine->add_postloadScript($blog_docs_site_setupJS); unset($blog_docs_site_setupJS);
		
		/*********************************************************************
		 * 
		 * Main HTML Content Creation - LEFT HAND SIDE CONTENT BOX
		 * 
		 *********************************************************************/
    
    
		 /**
		  * Tool Tip Tags 
		  */
		$tooltip_tag = $Templater->create_tooltip('/info/tooltip/tags');
		$tooltip_twitterdisplay = $Templater->create_tooltip('/info/tooltip/twitterdisplay');
		$tooltip_twitteraccnts = $Templater->create_tooltip('/info/tooltip/twitteraccnts');
		$tooltip_public = $Templater->create_tooltip('/info/tooltip/publicproject');
		
		
		/*********************************
		 * 
		 * Main HTML Content Creation
		 * Section: Editer Line
		 * 
		 ********************************/
		
		$editer_line = <<<EOEL
		
		    <div class="row-fluid">
			<div class="span12" style="text-align: right;">
			    <span style="border-bottom: 1px dotted #989898;"><span style="font-weight: bold;">Editing</span> {$Project->getName()} </span><img src="/img/set.gif" style="width: 16px; height: 16px; border-style: 0px solid none;" alt="Editing" /> (<span style="font-style: italic;"><a href="/edit/{$Project->getAlias()}/changes">View Changelog</a></span>)</span>
			</div>
		    </div>
EOEL;
		
		
		/*********************************
		 * 
		 * Main HTML Content Creation
		 * Section: Project Settings and Project Description
		 * 
		 ********************************/
		
		
		// 3 4x Spans
		$first_span_open = '<div class="row-fluid">';
		
		$proj_img = ($Project->getIconURL() !== false ? $Project->getIconURL() : '');
		$proj_public = ($Project->getIsVisible() === true ? 'checked="checked"' : '');
		$project_editor_html = <<<EOPE
		<form id="set_update" target="edjx_settings_update" method="POST" action="/edjx/settings/update/{$Project->getAlias()}">
		    <div class="span4" style="text-align: center;">
			<h2>Project Settings</h2>
			<div class="row-fluid">
			    <div class="span4" style="text-align: right; font-weight: bold">
				Title&nbsp;:<br />
				<img src="/img/spin.gif" id="descr_wait" name="settings_wait" style="height: 32px; width: 32px; display: none;" alt="Loading" />&nbsp;
			    </div>
			    <div class="span8">
				<input type="text" name="ib_text_newname" style="width: 85%;" value="{$Project->getName()}" />
			    </div>
			</div>
			<div class="row-fluid">
			    <div class="span4" style="text-align: right; font-weight: bold">
				Image&nbsp;:<br />
				<img src="/img/spin.gif" id="imag_wait" name="settings_wait" style="height: 32px; width: 32px; display: none;" alt="Loading" />&nbsp;
			    </div>
			    <div class="span8">
				<input type="text" name="ib_text_newimg" style="width: 85%;" value="{$proj_img}" />
			    </div>
			</div>
			<div class="row-fluid">
			    <div class="span4" style="text-align: right; font-weight: bold">
				{$tooltip_public} Public&nbsp;:<br />
				<img src="/img/spin.gif" id="visi_wait" name="settings_wait" style="height: 32px; width: 32px; display: none;" alt="Loading" />&nbsp;
			    </div>
			    <div class="span8">
				<input type="checkbox" name="cb_visibility" id="cb_visibility" style="width: 85%;" {$proj_public}/>
			    </div>
			</div>
		    </div>
		    <div class="span8" style="text-align: center;">
			<h2>Project Description</h2>
			<div class="row-fluid">
			    <div class="span4" style="text-align: right; font-weight: bold">
				Description<br />
				<img src="/img/spin.gif" id="descr_wait" name="settings_wait" style="height: 32px; width: 32px; display: none;" alt="Loading" />&nbsp;
			    </div>
			    <div class="span8">
				<textarea name="ta_description_new" style="height: 100px; width: 100%;">{$Project->getDescription()}</textarea>
			    </div>
			</div>
			<div class="row-fluid">
			    <div class="span4" style="text-align: right; font-weight: bold">
				&nbsp;
			    </div>
			    <div class="span8">
				<input type="submit" value="Update Settings & Description" name="set_update" />
			    </div>
			</div>
		    </div>
		</form>
EOPE;
		
		
				
				
				
		/*********************************
		 * 
		 * Main HTML Content Creation
		 * Section: Tags
		 * 
		 ********************************/
		$tags_init_html = <<<EOTINIT
		    <div class="span4" style="text-align: center;">
			<h2>Tags{$tooltip_tag}</h2>
			<div class="row-fluid">
			    <div class="span8">
				<input type="text" name="tagadd" id="tagadd" style="width: 100%!IMPORTANT;" onkeyup="TagsEDJX.tagaddChange_event();" onchange="TagsEDJX.tagaddChange_event();" />
			    </div>
			    <div class="span4">
				<button type="button" id="taggadd_button" onclick="TagsEDJX.tagAdd()" disabled="disabled">Add</button>
			    </div>
			</div>
			<div class="row-fluid" id="tagadd_invalid_alert" style="background-color: #FCC; text-align: center; font-style: italic; display: none;">
			    <div class="span12">
				Invalid Tag! a-z, 0-9 and underscore (_) only! Tags should be single words!
			    </div>
			</div>
			<div class="row-fluid" id="tagadd_invalid_exists" style="background-color: #FCC; text-align: center; font-style: italic; display: none;">
			    <div class="span12">
				That tag has already been added.
			    </div>
			</div>
			    <div id="taglistContainer" style="text-align: center;">
				<img src="/img/spin.gif" id="taglist_wait" name="taglist_wait" style="height: 32px; width: 32px;" alt="Loading" />
				<select option="width: 95%;" size="10" id="taglist" style="display: none;" name="taglist" onchange="TagsEDJX.tagSelected_event();"></select><br />
				<button type="button" id="taglist_btn" name="taglist_btn" style="display: none;" onclick="TagsEDJX.tagDelete_event()" disabled="disabled">Delete</button><br />
			    </div>
			<br />
			
		    </div>
EOTINIT;
			
			
		/*********************************
		 * 
		 * Main HTML Content Creation
		 * Section: Administration Level if Admin, Contributors Section
		 * 
		 ********************************/
		$user_init_admin_html = '';
		// TODO: Admin pre-addition - change to allow admin use
		if($_ADMINEDIT === false) {
		    $admin_str = "You're the lead maintainer";
		} else {
		    $admin_str = "You're administrating this project";
		}
		if($Project->userCanAdmin($_LOGGEDINUSER->get_userid(), $_ADMINEDIT)) {
		    // Indicates an admin user, this person can delegate a new lead user
		    $user_init_admin_html = <<<EOUINITADM
			<div class="row-fluid">
			    <div class="span12">
				{$admin_str}.<br /><a href="/edit/{$Project->getAlias()}/delegate">Delegate New Lead</a>
			    </div>
			</div>
EOUINITADM;
		//}
		
		/**
		 * Add onto the admin above if it exists
		 * This creates the deletion box. 
		 */
		$user_init_admin_html .= <<<EONONADMIN
			<div class="span12">
			    <img src="/img/spin.gif" id="contributors_contrib_wait" name="contributors_contrib_wait" style="height: 32px; width: 32px;" alt="Loading" />
			    <div class="row-fluid" id="contributors_select_container" style="display: none; visibility: hidden;">
				<div id="select_contrib_delete_error" style="display: none; visibility: hidden; background-color: #FCC; width: 85%;"></div>
				<select size="10" style="width: 80%;" id="select_contrib_listuser" onchange="UserContribEDJX.listUserChangeEvent();">
				</select><br />
				<button type="button" id="select_contrib_listuser_btn" disabled="disabled" onclick="UserContribEDJX.delEvent();">Delete User</button>
			    </div>
			</div>
EONONADMIN;
		
		/**
		 * User Search Box 
		 */
		$user_init_html = <<<EOUINIT
		<div class="span8" style="text-align: center;">
		    <h2>Contributors</h2>
		    <div class="row-fluid">
			<div class="span6" style="text-align: center;">
			    {$user_init_admin_html}
			</div>
			<div class="span6" style="text-align: center;">
			    <input type="text" style="width: 80%;" id="search_contrib_input" onkeyup="UserContribEDJX.searchChangeEvent()" onchange="UserContribEDJX.searchChangeEvent()" /><br />
			    <button type="button" disabled="disabled" id="search_contrib_addbtn" onclick="UserContribEDJX.searchEvent()">Search for User</button><br /><br />
			    <img src="/img/spin.gif" id="search_contrib_wait" name="search_contrib_wait" style="height: 32px; width: 32px; display: none; visibility: hidden;" alt="Loading" /><br />
			    <div id="select_contrib_search_nouser" style="display: none; visibility: hidden; background-color: #FCC; width: 85%;">No Users Found.</div>
			    <div id="select_contrib_search_invalid" style="display: none; visibility: hidden; background-color: #FCC; width: 85%;">Please use alphanumeric characters to search only. (Minimum Length: 4 Characters)</div>
			    <div id="select_contrib_search_error" style="display: none; visibility: hidden; background-color: #FCC; width: 85%;"></div>
			    <div id="select_contrib_container_add_user" style="display: none; visibility: hidden">
				<select size="7" style="width: 80%;" id="select_contrib" onchange="UserContribEDJX.searchSelect_change();">
				</select><br />
				<button type="button" id="select_contrib_addbtn" disabled="disabled" onclick="UserContribEDJX.addEvent();">Add User</button>
			    </div>
			</div>
		    </div>
		</div>
EOUINIT;
		} else {
		    $takeAdmin = "";
		    if($_LOGGEDINUSER->get_priv_adm() === true) {
			$takeAdmin = '<br /><a href="/admin/project/'.$Project->getAlias().'">Apply Sitewide Administrative Priviledges <img src="/img/set.gif" style="width: 16px; height: 16px; border-style: 0px solid none;" alt="Administrate" />.</a>';
		    }
		    $user_init_html = <<<EOUINIT
		<div class="span8" style="text-align: center;">
		    <h2>Contributors</h2>
		    <div class="row-fluid">
			<div class="span12" style="text-align: center; font-style: italic;">
			    Only Lead Maintainers can add and remove contributors
			    {$takeAdmin}
			</div>
		    </div>
		</div>
EOUINIT;
		}
		
		
		/**
		 * Create a website edit box
		 * Websites, Blogs, Documentation and RSS use a common ajax system and a common template
		 * @param string $div_prefix - This is the prefix for the names of all the items
		 * @param string $h2_title - This is the title of the box
		 * @return type 
		 */
		function editView_siteEditBox($div_prefix, $h2_title) {
		    global $Project;
		    /*
		     * IMPORTANT: Browsers where doing something unusual when I posted data from the first post "/edjx/{$div_prefix}/add/{$Project->getAlias()}"
		     * Therefore, the addChangeEvent in javascript, is adding the value to the submit button.
		     * Use that value in the AJAX
		     */
		    return <<<EOX
			<div class="span4" style="text-align: center;">
			    <iframe src="" class="hiddenElement" id="edjx_{$div_prefix}_add" name="edjx_{$div_prefix}_add"></iframe>
			    <iframe src="" class="hiddenElement" id="edjx_{$div_prefix}_del" name="edjx_{$div_prefix}_del"></iframe>
			    <h2>{$h2_title}</h2>
			    <div class="row-fluid">
			    <div class="span8">
				<form method="POST" action="/edjx/{$div_prefix}/add/{$Project->getAlias()}" target="edjx_{$div_prefix}_add" id="frm_{$div_prefix}_add" name="frm_{$div_prefix}_add" onsubmit="SiteEDJX.addEvent('{$div_prefix}');">
				    <input type="submit" class="hiddenElement" value="submit" name="submit_item" id="frm_sbm_{$div_prefix}" />
				    <input type="text" id="{$div_prefix}_add" name="add_item" style="width: 100%!IMPORTANT;" onkeyup="SiteEDJX.addChangeEvent('{$div_prefix}');" onchange="SiteEDJX.addChangeEvent('{$div_prefix}');" />
				</form>
			    </div>
			    <div class="span4">
				<button type="button" id="{$div_prefix}_add_button" onclick="SiteEDJX.add('{$div_prefix}')" disabled="disabled">Add</button>
			    </div>
			</div>
			<div class="row-fluid" id="{$div_prefix}_add_invalid_alert" style="background-color: #FCC; text-align: center; font-style: italic; display: none;">
			    <div class="span12">
				That {$div_prefix} URL was rejected.
			    </div>
			</div>
			<div class="row-fluid" id="{$div_prefix}_add_invalid_exists" style="background-color: #FCC; text-align: center; font-style: italic; display: none;">
			    <div class="span12">
				That {$div_prefix} has already been added.
			    </div>
			</div>
			    <div id="{$div_prefix}_container" style="text-align: center;">
				<img src="/img/spin.gif" id="{$div_prefix}_list_wait" name="{$div_prefix}_list_wait" style="height: 32px; width: 32px;" alt="Loading" />
				<form method="POST" action="/edjx/{$div_prefix}/del/{$Project->getAlias()}" target="edjx_{$div_prefix}_del" id="frm_{$div_prefix}_del" name="frm_{$div_prefix}_del">
				    <select option="width: 95%;" size="10" id="{$div_prefix}_list" name="del_item" style="display: none;" name="{$div_prefix}list" onchange="SiteEDJX.selectedEvent('{$div_prefix}');"></select><br />
				</form>
				<button type="button" id="{$div_prefix}_list_btn" name="{$div_prefix}_list_btn" style="display: none;" onclick="SiteEDJX.deleteEvent('{$div_prefix}')" disabled="disabled">Delete</button><br />
			    </div>
			</div>
EOX;
	//
		}
		
		/*********************************
		 * 
		 * Main HTML Content Creation
		 * Section: Call the above function and create the website, blog, docs edit boxes
		 * 
		 ********************************/
		$site_html = editView_siteEditBox('site', 'Websites');
		$blog_html = editView_siteEditBox('blog', 'Blogs');
		$docs_html = editView_siteEditBox('docs', 'Documentation');
		
		$rss_html = editView_siteEditBox('rss', 'RSS Feeds');
		
		$first_span_close = '</div>';
		
		
		
		/**
		 * Take all above that we have built, and load it into the template engine
		 * Everything is unset to free up memory. As we are about to duplicate it
		 * Comment the unsets if you need it later 
		 */
		$TemplateEngine->create_content_html($editer_line);		    unset($editer_line);
		$TemplateEngine->create_content_html($first_span_open);
		    $TemplateEngine->create_content_html($project_editor_html);	    unset($project_editor_html);
		$TemplateEngine->create_content_html($first_span_close);
		$TemplateEngine->create_content_html($first_span_open);
		    $TemplateEngine->create_content_html($tags_init_html);	    unset($tags_init_html);
		    $TemplateEngine->create_content_html($user_init_html);	    unset($user_init_html);
		$TemplateEngine->create_content_html($first_span_close);
		$TemplateEngine->create_content_html($first_span_open);
		    $TemplateEngine->create_content_html($site_html);		    unset($site_html);
		    $TemplateEngine->create_content_html($blog_html);		    unset($blog_html);
		    $TemplateEngine->create_content_html($docs_html);		    unset($docs_html);
		$TemplateEngine->create_content_html($first_span_close);
		$TemplateEngine->create_content_html($first_span_open);
		    $TemplateEngine->create_content_html($rss_html);		    unset($rss_html);
		$TemplateEngine->create_content_html($first_span_close);
		
		/*********************************************************************
		 * 
		 * Right Hand Side HTML Content Creation - RIGHT HAND SIDE CONTENT BOX
		 * 
		 *********************************************************************/
		
		/*********************************
		 * 
		 * Right Hand Side HTML Content Creation
		 * Section: Create the twitter editing block
		 * 
		 ********************************/
		$twitter_edit_box = '<div style="width: 100%; text-align: center;">';
		/*$isNoneSelected = $Project->hasTwitter() === true ? '' : ' selected';
		$twitters = $Project->getTwitters();
		$twitterDisplay = $Project->getTwitterToDisplay();
		$Project->hasTwitter() === true ? array_push($twitters, $twitterDisplay) : '';
		$listTwitters_withSelected = "";
		$listTwitters = "";
		foreach($twitters as $key => $value) {
		    if($value == $twitterDisplay) {
			$selected = ' selected';
		    } else {
			$selected = '';
		    }
		    $listTwitters_withSelected .= '<option value="'.$value.'"'.$selected.'>'.$value.'</option>';
		    $listTwitters .= '<option value="'.$value.'">'.$value.'</option>';
		}*/
		
		$twitter_edit_box .= <<<EOEB
		    <hr /><span style="font-weight: bold;">Display Twitter:{$tooltip_twitterdisplay}</span><br />
		    <div id="display_twitter_list_wait" name="display_twitter_list_wait"><img src="/img/spin.gif" style="height: 32px; width: 32px;" alt="Loading" /></div>
		    <select id="display_twitter" style="display: none;">
		    </select>
		    <button type="button" id="display_twitter_btn" style="display: none;" onclick="TwitterEDJX.updButtonEvent();" >Update</button><hr />
		    
		    <span style="font-weight: bold;">Associated Twitters:{$tooltip_twitteraccnts}</span><br />
		    <div id="display_twitter_assoc_wait" name="display_twitter_assoc_wait"><img src="/img/spin.gif" style="height: 32px; width: 32px;" alt="Loading" /></div>
		    <select id="assoc_twitter" style="display: none;" size="4" onchange="TwitterEDJX.updateEventAssoc();">
		    </select>
		    <button type="button" id="del_twitter_btn" style="display: none;" onclick="TwitterEDJX.delButtonEvent();" disabled="disabled">Delete</button><hr />
		    
		    <span style="font-weight: bold;">Add Twitter Account:</span><br />
		    <div id="display_add_invalid_chars" name="display_add_invalid_chars" style="display: none; font-weight: bold; color: #333; background-color: #FCC;">Invalid account name! You don't need to hash: Can only contain A-Z, a-z, 0-9, Underscore and full stop!</div>
		    <div id="display_add_invalid_exist" name="display_add_invalid_exist" style="display: none; font-weight: bold; color: #333; background-color: #FCC;">That account is already linked.</div>
		    <div id="display_add_list_wait" name="display_add_list_wait"><img src="/img/spin.gif" style="height: 32px; width: 32px;" alt="Loading" /></div>
		    <input type="text" style="width: 100%; display: none;" id="add_twitter_box" onkeyup="TwitterEDJX.updateEventAdd();" onchange="TwitterEDJX.updateEventAdd();" />
		    <button type="button" id="add_twitter_btn" style="display: none;" disabled="disabled" onclick="TwitterEDJX.addButtonEvent();" >Add</button><hr />
EOEB;
		$twitter_edit_box .= '</div>';
		
		// Create the sidebar itself and push the html into the templating system
		$TemplateEngine->create_sidebar_html(
		    $Templater->createSidebarItem('Edit Twitter Accounts', $twitter_edit_box)
		);
		
	    } else {
		$TemplateEngine->create_content_html($Templater->makeherounit('XP :: Woops!', 'To edit this project, you must be a maintainer!', '<button class="btn btn-primary btn-large" onclick="history.go(-1); return true;">Back</a>'));
	    }
	    
	    $TemplateEngine->render();
	} catch(InvalidProjectException $e) {
	    $gVAR['e'] = 404;
	    require_once('error_handler.php');
	    die();
	}
    } else {
	$gVAR['e'] = 404;
	require_once('error_handler.php');
	die();
    }
?>
